package com.wtwd.campus.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespCodeEntity;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.dao.*;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.model.vo.DeviceFlagVo;
import com.wtwd.campus.service.*;
import com.wtwd.campus.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2021/06/09
 * @description
 */
@Service
public class DeviceInfoServiceImpl implements DeviceInfoService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceInfoServiceImpl.class);

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CommandSendUtils commandSendUtils;

    @Autowired
    private DeviceClassPatternMapper deviceClassPatternMapper;

    @Autowired
    private OffLineBufferCmdMapper offLineBufferCmdMapper;

    @Autowired
    private LocationMapper locationMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private DeviceSettingMapper deviceSettingMapper;

    @Autowired
    private WhiteListMapper whiteListMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private H5Mapper h5Mapper;

    @Autowired
    private CommandRecordMapper commandRecordMapper;

    @Autowired
    private SosCallMapper sosCallMapper;

    @Autowired
    private DeviceFlagService deviceFlagService;


    /**
     * 流程整理
     * 1.通过类型和今日起始时间来确定起始时间,和结束时间
     * 2.查出这两个时间节点之间的数据，封装
     *
     * @param userId
     * @param type
     * @param year
     * @return
     * @throws ParseException
     */
    @Override
    public List<Map<String, Object>> getDeviceIncreased(Integer userId, Integer type, Integer year) throws ParseException {
        Date dayBeginTime = DateUtils.getDayBeginTime(new Date());   // 今日开始时间
        Date beginTime;    // 参与计算的开始时间
        Date endTime = new Date();    // 参与计算的截止时间
        switch (type) {
            case 0:   // 月度
                Calendar calendar = Calendar.getInstance();
                int currentYear = calendar.get(Calendar.YEAR);
                if (currentYear == year) {   // 如果是当前年
                    beginTime = DateUtils.getYearBeginTime(new Date());    // 开始时间
                } else {  // 不是当前年
                    beginTime = DateUtils.parse(year + "-01-01 00:00:00", DateUtils.dateFormat4);
                    calendar.setTime(beginTime);
                    int lastDayOfYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
                    calendar.set(Calendar.DAY_OF_YEAR, lastDayOfYear);
                    endTime = calendar.getTime();
                }
                break;
            case 1:   // 近30天
                beginTime = DateUtils.getAppointDay(dayBeginTime, -29);
                break;
            default:   // 近7天
                beginTime = DateUtils.getAppointDay(dayBeginTime, -6);
                break;
        }
        SysUser sysUser = userService.getSysUserByUserId(userId);
        List<Map<String, Object>> deviceNumList = deviceInfoMapper.getDeviceIncrease(beginTime.getTime(), endTime.getTime(), sysUser.getOrgCode());
        Map<Object, List<Map<String, Object>>> date = deviceNumList.stream().collect(Collectors.groupingBy(
                map -> {
                    if (type == 0) {
                        map.put("data", DateUtils.format(new Date((Long) map.get("data")), DateUtils.dateFormat13));//按日查看
                    } else {
                        map.put("data", DateUtils.format(new Date((Long) map.get("data")), DateUtils.dateFormat5));//按月查看
                    }
                    return map;
                }
        ));
        HashMap<String, Object> restMap = new HashMap<>();
        date.forEach((key, value) -> {
            restMap.put((String) ((Map<String, Object>) key).get("data"), value.size());
        });
        // 创建返回结果的集合
        List<Map<String, Object>> resultList = new ArrayList<>();
        do {
            String data = "";
            if (type == 0) {
                data = DateUtils.format(beginTime, DateUtils.dateFormat13);
            } else {
                data = DateUtils.format(beginTime, DateUtils.dateFormat5);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("increasedCount", restMap.get(data) != null ? restMap.get(data) : 0);
            map.put("date", data);
            // 每次加一个月或者一天
            beginTime = (type == 0 ? DateUtils.getAppointMonth(beginTime, 1) : DateUtils.getAppointDay(beginTime, 1));
            resultList.add(map);
        }
        while (beginTime.before(endTime));
        return resultList;
    }

    //获取设备相关信息的数量(包括设备在线数量，离线数量，校园卡绑定数量，未绑定数量,总数)
    @Override
    public Map<String, Object> getDeviceCountInfo(String orgCode) {
        int online = 0;//在线数
        int offline = 0;//离线数
        int bind = 0;//绑定数
        int notBind = 0;//未绑定数
        //根据用户获取所有校园卡信息
        List<DeviceInfo> deviceList = deviceInfoMapper.getDeviceListByOrgCode(orgCode);
        if (deviceList != null && deviceList.size() > 0) {
            for (DeviceInfo deviceInfo : deviceList) {
                if (deviceInfo.getStudentId() == null) {//记录为未绑定校园卡数量
                    notBind++;
                } else {
                    bind++;
                }
                if (deviceInfo.getLastUpTime() != null) {
                    Long intervalTime = new Date().getTime() - deviceInfo.getLastUpTime();
                    if (intervalTime >= Constants.OFF_LINE_TIME) {//离线
                        offline++;
                    } else {//在线
                        online++;
                    }
                } else {//最后上传时间为null时，离线数量+1
                    offline++;
                }
            }
        }
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("online", online);
        restMap.put("offline", offline);
        restMap.put("bind", bind);
        restMap.put("notBind", notBind);
        restMap.put("totalCount", deviceList != null ? deviceList.size() : 0);
        return restMap;
    }

    //条件查询设备SIM卡列表信息
    @Override
    public DeviceInfo getDeviceInfoByStudentId(Integer stuId) {
        return deviceInfoMapper.getDeviceInfoByStudentId(stuId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateBindDevice(Integer oldDeviceId, VoStudent voStudent) {
        //解绑原有设备
        deviceInfoMapper.bindDevice(null, oldDeviceId);
        //获取绑定设备时，设备需要同步的学校
        School school = schoolMapper.getSchoolInfoBySchoolId(voStudent.getSchoolId());
        //绑定设备的同时,同步设备到该学生的学校
        Integer rest = deviceInfoMapper.bindDeviceAndSynchronizationOrg(voStudent.getStuId(), voStudent.getDeviceId(), school.getOrgCode(), school.getSchoolName());
        return rest;
    }

    @Override
    public List<Map<String, Object>> getDeviceImeiAndDeviceIdByOrgCodeLikeImei(String imei, String orgCode) {
        return deviceInfoMapper.getDeviceImeiAndDeviceIdByOrgCodeLikeImei(imei, orgCode);
    }

    /**
     * 条件查询设备SIM卡列表信息
     *
     * @param data
     * @return
     */
    @Override
    public Map<String, Object> getSimCardList(QuerySimCardDataVo data) {
        Page<Map<String, Object>> page = new Page<>(data.getCurrPage(), data.getPageSize());
        IPage<Map<String, Object>> simCardList = deviceInfoMapper.getSimCardList(data, page);
        Map<String, Object> result = disposalData(simCardList);
        return result;
    }

    @Override
    public RespEntity modifySimCard(ModifyDeviceDataVo data) {
        //判断修改的sim卡号是否已经存在其他设备上
        Integer num = deviceInfoMapper.getDeviceBySimCard(data.getSim_card());
        if (num > 0) {
            return new RespEntity(RespCode.NUMBER_HAD_USED);
        } else {
            //修改sim卡号
            Integer i = deviceInfoMapper.modifyDeviceSimCard(data);
            return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
        }
    }

    @Override
    public Map<String, Object> getDeviceInfoListByCondition(HashMap<String, Object> searchMap, Page<Object> page) {
        IPage<Map<String, Object>> data = deviceInfoMapper.getDeviceInfoListByCondition(searchMap, page);
        //构件返值数据
        List<Map<String, Object>> deviceList = data.getRecords();
        deviceList.stream().forEach(e -> {
            //把null归于无屏幕
            Integer ifScreen = (Integer) e.get("if_screen");
            ifScreen = ifScreen == null ? 2 : ifScreen;
            e.put("if_screen", ifScreen);
            Integer workingPattern = (Integer) e.get("working_pattern");
            if (workingPattern == null) {
                e.put("realTimeMode", Constants.UP_INTERVAL);
                e.put("powerSaveMode", Constants.POWER_SAVING_MODEL_UP_INTERVAL);
                e.put("type", Constants.DEFAULT_WORK_PATTERN);
            } else if (workingPattern == Constants.DEFAULT_WORK_PATTERN) {
                e.put("realTimeMode", e.get("up_interval"));
                e.put("powerSaveMode", Constants.POWER_SAVING_MODEL_UP_INTERVAL);
                e.put("type", Constants.DEFAULT_WORK_PATTERN);
            } else if (workingPattern == Constants.POWER_SAVING_MODEL) {
                e.put("realTimeMode", Constants.UP_INTERVAL);
                e.put("powerSaveMode", e.get("up_interval"));
                e.put("type", Constants.POWER_SAVING_MODEL);
            }
           /* if (e.get("working_pattern") == null) {
                e.put("working_pattern", Constants.DEFAULT_WORK_PATTERN);
            }
            if (e.get("up_interval") == null) {
                e.put("up_interval", Constants.UP_INTERVAL);
            }*/
        });
        Iterator<Map<String, Object>> iterator = deviceList.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> map = iterator.next();
           /* //当前时间-默认离线时间间隔<=最后上传时间
            if ((long) map.get("last_up_time") >= (long) searchMap.get("time")) {
                map.put("start", "在线");
                map.remove("last_up_time");
                continue;
            } else {
                map.put("start", "离线");
                map.remove("last_up_time");
                continue;
            }*/
            boolean b = deviceOnline((String) map.get("imei"));
            map.put("start", b ? "在线" : "离线");
            map.remove("last_up_time");
        }
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("date", deviceList);
        restMap.put("total", data.getTotal());
        return restMap;
    }

    @Override
    public List<Map<String, Object>> getModelByOrgCode(String orgCode) {
        return deviceInfoMapper.getModelByOrgCode(orgCode);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteDeviceById(Integer deviceId) {
        //删除白名单数据
        whiteListMapper.delDeviceAllWhiteListByDeviceId(deviceId, 0);
        //删除课堂模式数据
        deviceClassPatternMapper.delDeviceAllClassesPatternByDeviceId(deviceId);
        //删除设备设置表数据
        deviceSettingMapper.delDeviceSettingByDeviceId(deviceId);
        //删除SOS号码
        deviceSettingMapper.deleteSOSList(deviceId);
        //下发绑定关系指令

        //删除设备表数据
        return deviceInfoMapper.deleteDeviceById(deviceId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer saveDeviceInfo(DeviceInfo deviceInfo) {
        deviceInfo.setCreateTime(new Date().getTime());
        deviceInfo.setUpdateTime(new Date().getTime());
        Integer rest = deviceInfoMapper.saveDeviceInfo(deviceInfo);
        //添加设备时初始化设备设置表
        DeviceSetting deviceSetting = new DeviceSetting();
        deviceSetting.setDeviceId(deviceInfo.getDeviceId());
        deviceSetting.setImei(deviceInfo.getImei());
        deviceSettingMapper.addDeviceSetting(deviceSetting);
        //将缓存中的未入库imei删掉
        List<String> list = new ArrayList<>();
        list.add(deviceInfo.getImei());
        redisService.deleteUnInStorageList(list);
        return rest;
    }

    @Override
    public RespCodeEntity checkDeviceInfo(DeviceInfo deviceInfo) {
        //鉴别imei号是否重复
        DeviceInfo oldDeviceInfo = deviceInfoMapper.getDeviceInfoByImei(deviceInfo.getImei());
        if (oldDeviceInfo != null) {
            return new RespCodeEntity(RespCode.IMEI_EXIT);
        }
        return new RespCodeEntity(RespCode.SUCCESS);
    }

    @Override
    public List<ExcelExportDeviceInfo> ExcelExportDeviceInfo(HashMap<String, Object> searchMap) {
        List<ExcelExportDeviceInfo> excelExportDeviceInfos = deviceInfoMapper.ExcelExportDeviceInfo(searchMap);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Iterator<ExcelExportDeviceInfo> iterator = excelExportDeviceInfos.iterator();
        while (iterator.hasNext()) {
            ExcelExportDeviceInfo exportDeviceInfo = iterator.next();
            Integer ifScreen = exportDeviceInfo.getIfScreen();
            ifScreen = ifScreen == null ? 2 : ifScreen;
            String screen = "";
            if (ifScreen == 0) {
                screen = "无屏";
            } else if (ifScreen == 1) {
                screen = "有屏";
            }
            exportDeviceInfo.setScreen(screen);
            if (exportDeviceInfo.getLastUpTime() >= (long) searchMap.get("time")) {
                exportDeviceInfo.setStart("在线");
            } else {
                exportDeviceInfo.setStart("离线");
            }
//            工作模式1定位模式  2省电模式 3无GPS模式 4无定位模式 5短信模式
            Date date = new Date(Long.parseLong(exportDeviceInfo.getCreateTime()));
            String tiem = simpleDateFormat.format(date);
            exportDeviceInfo.setCreateTime(tiem);
            if (exportDeviceInfo.getWorkingPattern() != null) {
                if (exportDeviceInfo.getWorkingPattern() == 1) {
                    exportDeviceInfo.setWorkingModel("定位模式");
                }
                if (exportDeviceInfo.getWorkingPattern() == 2) {
                    exportDeviceInfo.setWorkingModel("省电模式");
                }
                if (exportDeviceInfo.getWorkingPattern() == 3) {
                    exportDeviceInfo.setWorkingModel("无GPS模式");
                }
                if (exportDeviceInfo.getWorkingPattern() == 4) {
                    exportDeviceInfo.setWorkingModel("无定位模式");
                }
                if (exportDeviceInfo.getWorkingPattern() == 5) {
                    exportDeviceInfo.setWorkingModel("短信模式");
                }
            }
        }
        return excelExportDeviceInfos;
    }

    @Override
    public DeviceSetting getDeviceSettingByDeviceId(Integer deviceId) {
        return deviceSettingMapper.getDeviceSettingByDeviceId(deviceId);
    }

    @Override
    public RespEntity importThirdPartDevice(MultipartFile file, HttpServletResponse response) {
        String fileName = file.getOriginalFilename();
        if (!ExcelUtils.validateExcel(fileName)) {
            return new RespEntity(RespCode.FILE_FORMAT_ERROR);
        }
        //导出失败信息记录
        List<ExcelThirdPartDevice> failMess = new ArrayList<>();
        //导出失败文件信息
        String path = "";
        //读取文件信息
        List<ExcelThirdPartDevice> importList = null;
        try {
            importList = MyExcelUtils.importExcel(file, 1, 1, ExcelThirdPartDevice.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (importList != null && importList.size() > 0) {
            //过滤格式不对的数据
            Iterator<ExcelThirdPartDevice> iterator = importList.iterator();
            while (iterator.hasNext()) {
                ExcelThirdPartDevice e = iterator.next();
                //客户id只能是数字
                String cusIdRegex = "^[0-9]+$";
                if (!e.getCusId().matches(cusIdRegex)) {
                    e.setRemark("客户id格式有误，仅能为数字");
                    failMess.add(e);
                    iterator.remove();
                    continue;
                }
                //客户类型的校验
                if (!("H5".equalsIgnoreCase(e.getCusType()) || "和校园".equals(e.getCusType()) || "沃特API".equals(e.getCusType()))) {
                    e.setRemark("客户类型有误");
                    failMess.add(e);
                    iterator.remove();
                    continue;
                }
                //校验imei的长度
                if (e.getImei().length() > 15) {
                    e.setRemark("imei太长，不符合规范");
                    failMess.add(e);
                    iterator.remove();
                    continue;
                }
                //如果客户id不存在也过滤掉
                Integer cusId = Integer.valueOf(e.getCusId());
                String cusType = e.getCusType();
                if ("H5".equalsIgnoreCase(cusType)) {
                    //从h5客户表中查询客户
                    String appKey = h5Mapper.getAppKeyBuCusId(cusId);
                    if (appKey == null) {
                        e.setRemark("该客户不存在");
                        failMess.add(e);
                        iterator.remove();
                        continue;
                    }
                } else {
                    //从客户表中查询
                    SysCustomer customerInfo = customerMapper.getCustomerInfoById(cusId);
                    if (customerInfo == null) {
                        e.setRemark("该客户不存在");
                        failMess.add(e);
                        iterator.remove();
                        continue;
                    }
                }
            }
            if (importList.size() > 0) {
                //过滤掉已经存在imei设备
                List<String> list = new ArrayList<>();
                importList.stream().forEach(e -> {
                    list.add(e.getImei());
                });
                List<String> imeiList = deviceInfoMapper.getImeiListByImeiList(list);
                if (imeiList.size() != 0) {
                    Iterator<ExcelThirdPartDevice> iterator1 = importList.iterator();
                    while (iterator1.hasNext()) {
                        ExcelThirdPartDevice e = iterator1.next();
                        if (imeiList.contains(e.getImei())) {
                            e.setRemark("该设备已存在");
                            failMess.add(e);
                            iterator1.remove();
                        }
                    }
                }
            }
            if (importList.size() > 0) {
                //过滤掉重复的imei号
                List<ExcelThirdPartDevice> judge = new ArrayList<>(importList);
                Iterator<ExcelThirdPartDevice> iterator1 = importList.iterator();
                while (iterator1.hasNext()) {
                    ExcelThirdPartDevice next = iterator1.next();
                    int i = 0;
                    for (ExcelThirdPartDevice device : judge) {
                        if (device.getImei().equals(next.getImei())) {
                            i++;
                        }
                    }
                    if (i > 1) {
                        next.setRemark("该imei在导入信息中重复");
                        failMess.add(next);
                        iterator1.remove();
                    }
                }
            }
            if (importList.size() > 0) {
                //构建数据并存入数据库
                List<DeviceInfo> addList = new ArrayList<>();
                importList.stream().forEach(e -> {
                    DeviceInfo deviceInfo = new DeviceInfo();
                    deviceInfo.setImei(e.getImei());
                    deviceInfo.setModel("E15");
                    deviceInfo.setCreateTime(System.currentTimeMillis());
                    deviceInfo.setUpdateTime(System.currentTimeMillis());
                    deviceInfo.setCustomerId(Integer.valueOf(e.getCusId()));
                    Integer deviceType = 0;
                    switch (e.getCusType()) {
                        case "H5":
                            deviceType = Constants.H5_DEVICE;
                            break;
                        case "h5":
                            deviceType = Constants.H5_DEVICE;
                            break;
                        case "和校园":
                            deviceType = Constants.HXY_DEVICE;
                            break;
                        case "沃特API":
                            deviceType = Constants.CUSTOMER_DEVICE;
                            break;
                        default:
                            break;
                    }
                    deviceInfo.setDeviceType(deviceType);
                    deviceInfo.setCustomerId(Integer.parseInt(e.getCusId()));
                    addList.add(deviceInfo);
                });
                //批量插入
                deviceInfoMapper.addSomeThirdPartDevice(addList);
                //初始化设备设置表
                deviceSettingMapper.batchInitializeDeviceSetting(addList);
                //删除缓存中为入库的imei
                List<String> list = new ArrayList<>();
                addList.stream().forEach(e -> {
                    list.add(e.getImei());
                });
                redisService.deleteUnInStorageList(list);
            }
            //导出失败文件信息
            Integer failNum = 0;
            if (failMess != null && failMess.size() > 0) {
                failNum = failMess.size();
                path = MyExcelUtils.exportExcel(failMess, "第三设备导入失败信息", "设备信息", ExcelThirdPartDevice.class, "第三方设备导入失败信息.xls", response);
            }
            //构建返回信息
            Map<String, Object> map = new HashMap<>();
            map.put("path", path);
            map.put("failNum", failNum);
            map.put("successNum", importList != null ? importList.size() : 0);
            return new RespEntity(RespCode.SUCCESS, map);
        }
        return new RespEntity(RespCode.WRITE_IMPORT_DATA);
    }

    @Override
    public RespEntity importNXDevice(MultipartFile file, HttpServletResponse response, String model) {
        String fileName = file.getOriginalFilename();
        if (!ExcelUtils.validateExcel(fileName)) {
            return new RespEntity(RespCode.FILE_FORMAT_ERROR);
        }
        //导出失败信息记录
        List<ExcelThirdPartDevice> failMess = new ArrayList<>();
        //导出失败文件信息
        String path = "";
        //读取文件信息
        List<ExcelNXDevice> importList = null;
        try {
            importList = MyExcelUtils.importExcel(file, 0, 1, ExcelNXDevice.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (importList != null && importList.size() > 0) {
            //导入所有设备
            //构建数据并存入数据库
            List<DeviceInfo> addList = new ArrayList<>();
            importList.stream().forEach(e -> {
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setImei(e.getImei());
                deviceInfo.setModel(model);
                deviceInfo.setCreateTime(System.currentTimeMillis());
                deviceInfo.setUpdateTime(System.currentTimeMillis());
                Integer deviceType = 3;
                deviceInfo.setDeviceType(deviceType);
                deviceInfo.setCustomerId(4);
                addList.add(deviceInfo);
            });
            //批量插入
            int i = deviceInfoMapper.addSomeThirdPartDevice(addList);
            //删除缓存中为入库的imei
            List<String> list = new ArrayList<>();
            addList.stream().forEach(e -> {
                list.add(e.getImei());
            });
            redisService.deleteUnInStorageList(list);
            //初始化设备设置表
            Integer integer = deviceSettingMapper.batchInitializeDeviceSetting(addList);
            logger.info("导入宁夏设备".concat(String.valueOf(importList.size())).concat("成功数量：".concat(String.valueOf(i))));
        }
        return new RespEntity(RespCode.SUCCESS);
    }

    @Override
    public DeviceInfo getDeviceInfoByRfid(String rfid) {
        return deviceInfoMapper.getDeviceInfoByRfid(rfid);
    }

    @Override
    public RespEntity importVcomLtDevice(MultipartFile file, HttpServletResponse response) {
        String fileName = file.getOriginalFilename();
        if (!ExcelUtils.validateExcel(fileName)) {
            return new RespEntity(RespCode.FILE_FORMAT_ERROR);
        }
        //导出失败信息记录
        List<ExcelImportLtDeviceInfo> failMessages = new ArrayList<>();
        //导出失败文件信息
        String path = "";
        //记录需要添加设备信息
        List<DeviceInfo> deviceInfos = new ArrayList<>();
        //读取文件信息
        List<ExcelImportLtDeviceInfo> excelImportDeviceInfos = null;
        try {
            excelImportDeviceInfos = MyExcelUtils.importExcel(file, 1, 1, ExcelImportLtDeviceInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (excelImportDeviceInfos != null && excelImportDeviceInfos.size() > 0) {
            aa:
            for (ExcelImportLtDeviceInfo excelImportDeviceInfo : excelImportDeviceInfos) {
                if (StringUtils.isBlank(excelImportDeviceInfo.getImei()) || StringUtils.isBlank(excelImportDeviceInfo.getModel()) || StringUtils.isBlank(excelImportDeviceInfo.getScreen()) || StringUtils.isBlank(excelImportDeviceInfo.getDeviceKey())
                        || StringUtils.isBlank(excelImportDeviceInfo.getDeviceSecret()) || StringUtils.isBlank(excelImportDeviceInfo.getDeviceKey())) {
                    ExcelImportLtDeviceInfo importDeviceInfo = new ExcelImportLtDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setDeviceKey(excelImportDeviceInfo.getDeviceKey());
                    importDeviceInfo.setDeviceSecret(excelImportDeviceInfo.getDeviceSecret());
                    importDeviceInfo.setProductKey(excelImportDeviceInfo.getProductKey());
                    importDeviceInfo.setMessage("必传参数为空");
                    failMessages.add(importDeviceInfo);
                    continue;
                }
                DeviceInfo deviceInfoByImei = deviceInfoMapper.getDeviceInfoByImei(excelImportDeviceInfo.getImei());
                if (deviceInfoByImei != null) {
                    ExcelImportLtDeviceInfo importDeviceInfo = new ExcelImportLtDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setDeviceKey(excelImportDeviceInfo.getDeviceKey());
                    importDeviceInfo.setDeviceSecret(excelImportDeviceInfo.getDeviceSecret());
                    importDeviceInfo.setProductKey(excelImportDeviceInfo.getProductKey());
                    importDeviceInfo.setMessage("已经存在该imei号的设备");
                    failMessages.add(importDeviceInfo);
                    continue;
                }
                //excel中是否重复导入
                if (deviceInfos != null && deviceInfos.size() > 0) {
                    for (DeviceInfo deviceInfo : deviceInfos) {
                        if (deviceInfo.getImei().equals(excelImportDeviceInfo.getImei())) {
                            ExcelImportLtDeviceInfo importDeviceInfo = new ExcelImportLtDeviceInfo();
                            importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                            importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                            importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                            importDeviceInfo.setDeviceKey(excelImportDeviceInfo.getDeviceKey());
                            importDeviceInfo.setDeviceSecret(excelImportDeviceInfo.getDeviceSecret());
                            importDeviceInfo.setProductKey(excelImportDeviceInfo.getProductKey());
                            importDeviceInfo.setMessage("重复导入imei号设备");
                            failMessages.add(importDeviceInfo);
                            continue aa;
                        }
                    }
                }
                //是否有屏幕这个字段只能填是或否
                String screen = excelImportDeviceInfo.getScreen();
                if (!("有屏".equals(screen) || "无屏".equals(screen))) {
                    ExcelImportLtDeviceInfo importDeviceInfo = new ExcelImportLtDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setDeviceKey(excelImportDeviceInfo.getDeviceKey());
                    importDeviceInfo.setDeviceSecret(excelImportDeviceInfo.getDeviceSecret());
                    importDeviceInfo.setProductKey(excelImportDeviceInfo.getProductKey());
                    importDeviceInfo.setMessage("未按照规范填写是否有屏");
                    failMessages.add(importDeviceInfo);
                    continue aa;
                }
                //记录可以成功添加的设备
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setImei(excelImportDeviceInfo.getImei());
                deviceInfo.setModel(excelImportDeviceInfo.getModel());
                deviceInfo.setCreateTime(new Date().getTime());
                deviceInfo.setExchangePlatform(1);
                deviceInfo.setDeviceKey(excelImportDeviceInfo.getDeviceKey());
                deviceInfo.setDeviceSecret(excelImportDeviceInfo.getDeviceSecret());
                deviceInfo.setProductKey(excelImportDeviceInfo.getProductKey());
                deviceInfo.setUpdateTime(new Date().getTime());
                Integer ifScreen = screen.equals("有屏") ? 1 : 0;
                deviceInfo.setIfScreen(ifScreen);
                if (!StringUtils.isBlank(excelImportDeviceInfo.getRfid())) {
                    deviceInfo.setRfid(excelImportDeviceInfo.getRfid());
                }
                //设备属于vcom设备
                deviceInfo.setCustomerId(1);
                deviceInfo.setDeviceType(5);
                deviceInfo.setExchangePlatform(1);
                deviceInfos.add(deviceInfo);
                continue;
            }
        }
        //批量添加设备
        if (deviceInfos != null && deviceInfos.size() > 0) {
            Integer rest = deviceInfoMapper.batchVcomLtDevice(deviceInfos);
            //批量初始化设备设置表
            deviceSettingMapper.batchInitializeDeviceSetting(deviceInfos);
            //删除缓存中为入库的imei
            List<String> list = new ArrayList<>();
            deviceInfos.stream().forEach(e -> {
                list.add(e.getImei());
            });
            redisService.deleteUnInStorageList(list);
        }
        //导出失败文件信息
        Integer failNum = 0;
        if (failMessages != null && failMessages.size() > 0) {
            failNum = failMessages.size();
            path = MyExcelUtils.exportExcel(failMessages, "设备信息", "设备信息", ExcelImportLtDeviceInfo.class, "设备文件导入失败信息.xls", response);
        }
        //构建返回值集合
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("path", path);
        restMap.put("failNum", failNum);
        restMap.put("successNum", deviceInfos != null ? deviceInfos.size() : 0);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

    @Override
    public Boolean authMonitorNumber(Integer deviceId, String number) {
        List<DeviceSOSList> sosCalls = sosCallMapper.getSosCallService(deviceId);
        List<DeviceWhiteList> deviceWhiteLists = whiteListMapper.getWhiteListByDeviceId(deviceId, 2);
        List<String> phones = new ArrayList<>();
        if (sosCalls != null && sosCalls.size() > 0) {
            List<String> sosPhones = sosCalls.stream().map(DeviceSOSList::getSosPhone).collect(Collectors.toList());
            phones.addAll(sosPhones);
        }
        if (deviceWhiteLists != null && deviceWhiteLists.size() > 0) {
            List<String> whites = deviceWhiteLists.stream().map(DeviceWhiteList::getWhitePhone).collect(Collectors.toList());
            phones.addAll(whites);
        }
        if (phones != null && phones.size() > 0) {
            return phones.contains(number);
        } else {
            return true;
        }
    }

    @Override
    public boolean bathAddDeviceInfo(List<DeviceInfo> deviceInfos) {
        Integer rest = deviceInfoMapper.batchSaveCustomerDevice(deviceInfos);
        //批量初始化设备设置表
        deviceSettingMapper.batchInitializeDeviceSetting(deviceInfos);
        return rest > 0 ? true : false;
    }

    @Override
    public List<DeviceFlagVo> getDeviceLockCardInfoByOrgCode(String orgCode, Integer flag) {
        return deviceFlagService.getDeviceLockCardInfoByOrgCode(orgCode,flag);
    }

    @Override
    public List<DeviceFlagVo> getDeviceLockDeviceInfoByOrgCode(String orgCode, Integer flag) {
        return deviceFlagService.getDeviceLockDeviceInfoByOrgCode(orgCode,flag);
    }

    @Override
    public List<DeviceFlagVo> getDeviceLockNetInfoByOrgCode(String orgCode, Integer flag) {
        return deviceFlagService.getDeviceLockNetInfoByOrgCode(orgCode,flag);
    }

    @Override
    public List<DeviceInfo> getDeviceByAll() {
        return deviceInfoMapper.getDeviceByAll();
    }

    @Override
    public RespEntity importVcomDevice(MultipartFile file, HttpServletResponse response) {
        String fileName = file.getOriginalFilename();
        if (!ExcelUtils.validateExcel(fileName)) {
            return new RespEntity(RespCode.FILE_FORMAT_ERROR);
        }
        //导出失败信息记录
        List<ExcelImportDeviceInfo> failMessages = new ArrayList<>();
        //导出失败文件信息
        String path = "";
        //记录需要添加设备信息
        List<DeviceInfo> deviceInfos = new ArrayList<>();
        //读取文件信息
        List<ExcelImportDeviceInfo> excelImportDeviceInfos = null;
        try {
            excelImportDeviceInfos = MyExcelUtils.importExcel(file, 1, 1, ExcelImportDeviceInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (excelImportDeviceInfos != null && excelImportDeviceInfos.size() > 0) {
            aa:
            for (ExcelImportDeviceInfo excelImportDeviceInfo : excelImportDeviceInfos) {
                if (StringUtils.isBlank(excelImportDeviceInfo.getImei()) || StringUtils.isBlank(excelImportDeviceInfo.getModel()) || StringUtils.isBlank(excelImportDeviceInfo.getScreen())) {
                    ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setMessage("必传参数为空");
                    failMessages.add(importDeviceInfo);
                    continue;
                }
                DeviceInfo deviceInfoByImei = deviceInfoMapper.getDeviceInfoByImei(excelImportDeviceInfo.getImei());
                if (deviceInfoByImei != null) {
                    ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setMessage("已经存在该imei号的设备");
                    failMessages.add(importDeviceInfo);
                    continue;
                }
                //excel中是否重复导入
                if (deviceInfos != null && deviceInfos.size() > 0) {
                    for (DeviceInfo deviceInfo : deviceInfos) {
                        if (deviceInfo.getImei().equals(excelImportDeviceInfo.getImei())) {
                            ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                            importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                            importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                            importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                            importDeviceInfo.setMessage("重复导入imei号设备");
                            failMessages.add(importDeviceInfo);
                            continue aa;
                        }
                    }
                }
                //是否有屏幕这个字段只能填是或否
                String screen = excelImportDeviceInfo.getScreen();
                if (!("有屏".equals(screen) || "无屏".equals(screen))) {
                    ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setMessage("未按照规范填写是否有屏");
                    failMessages.add(importDeviceInfo);
                    continue aa;
                }
                //记录可以成功添加的设备
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setImei(excelImportDeviceInfo.getImei());
                deviceInfo.setModel(excelImportDeviceInfo.getModel());
                deviceInfo.setCreateTime(new Date().getTime());
                deviceInfo.setUpdateTime(new Date().getTime());
                Integer ifScreen = screen.equals("有屏") ? 1 : 0;
                deviceInfo.setIfScreen(ifScreen);
                if (!StringUtils.isBlank(excelImportDeviceInfo.getRfid())) {
                    deviceInfo.setRfid(excelImportDeviceInfo.getRfid());
                }
                //设备属于vcom设备
                deviceInfo.setCustomerId(1);
                deviceInfo.setDeviceType(5);
                deviceInfos.add(deviceInfo);
                continue;
            }
        }
        //批量添加设备
        if (deviceInfos != null && deviceInfos.size() > 0) {
            Integer rest = deviceInfoMapper.batchSaveCustomerDevice(deviceInfos);
            //批量初始化设备设置表
            deviceSettingMapper.batchInitializeDeviceSetting(deviceInfos);
            //删除缓存中为入库的imei
            List<String> list = new ArrayList<>();
            deviceInfos.stream().forEach(e -> {
                list.add(e.getImei());
            });
            redisService.deleteUnInStorageList(list);
        }
        //导出失败文件信息
        Integer failNum = 0;
        if (failMessages != null && failMessages.size() > 0) {
            failNum = failMessages.size();
            path = MyExcelUtils.exportExcel(failMessages, "设备信息", "设备信息", ExcelImportDeviceInfo.class, "设备文件导入失败信息.xls", response);
        }
        //构建返回值集合
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("path", path);
        restMap.put("failNum", failNum);
        restMap.put("successNum", deviceInfos != null ? deviceInfos.size() : 0);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

   /* @Override
    public LtAuthKey getLtAuthKeyByImei(String imei) {
        DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByImei(imei);
        LtAuthKey ltAuthKey = new LtAuthKey();
        if (deviceInfo==null||deviceInfo.getExchangePlatform()==null){
            ltAuthKey.setDeviceKey("");
            ltAuthKey.setDeviceSecret("");
            ltAuthKey.setProductKey("");
            return ltAuthKey;
        }
        if (deviceInfo.getExchangePlatform()!=1){
            ltAuthKey.setDeviceKey("");
            ltAuthKey.setDeviceSecret("");
            ltAuthKey.setProductKey("");
            return ltAuthKey;
        }
        ltAuthKey.setDeviceKey(deviceInfo.getDeviceKey());
        ltAuthKey.setDeviceSecret(deviceInfo.getDeviceSecret());
        ltAuthKey.setProductKey(deviceInfo.getProductKey());
        return ltAuthKey;
    }*/

    @Override
    public Map<String, Object> getThirdPartDeviceList(ThirdPartDeviceVO data) {
        if (data.getMode() == 0) {
            //表示对于工作模式查询全部
            data.setMode(null);
        }
        Integer type = data.getType();
        //因为h5的客户和其他客户信息存放不在一张表中，因此需要分开
        List<Map<String, Object>> result;
        if (type == Constants.H5_DEVICE) {
            //h5设备查询
            result = deviceSettingMapper.getH5ThirdPartDeviceList(data);
        } else {
            result = deviceSettingMapper.getOtherThirdPartDeviceList(data);
        }
        //进行是否在线的判断
        Integer flag = data.getIsOnline();
        List<Map<String, Object>> online = new ArrayList<>();
        List<Map<String, Object>> offline = new ArrayList<>();
        List<String> imeis = result.stream().map(e -> (String) e.get("imei")).collect(Collectors.toList());
        Map<String, Boolean> onlineMap = deviceFlagService.bathGetDeviceOnline(imeis);
        result.stream().forEach(e -> {
            boolean isOnline = onlineMap.get(e.get("imei"));
            e.put("isOnline", isOnline ? "在线" : "离线");
            if (isOnline) {
                online.add(e);
            } else {
                offline.add(e);
            }
        });
        //自己构造分页
        int start = data.getCurPage() * data.getPageSize();
        List<Map<String, Object>> dealList;
        if (flag == 2) {
            //表示查全部
            dealList = result;
        } else {
            dealList = flag == 0 ? offline : online;
        }
        int total = dealList.size();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = start; i < total; i++) {
            if (i == start + data.getPageSize()) {
                break;
            }
            list.add(dealList.get(i));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("data", list);
        return map;
    }

    @Override
    public List<DeviceInfo> getDeviceInfoListByStuIdList(List<Integer> list) {
        return deviceInfoMapper.getDeviceInfoListByStuIdList(list);
    }

    @Override
    public int unBindingStudentWithDevice(Integer stuId) {
        return deviceInfoMapper.unBindingStudentWithDevice(stuId);
    }

    @Override
    public Map<String, Object> getModeStatusByDeviceId(Integer deviceId, String imei) {
      /*  //根据imei获取设备设置信息
        DeviceSetting deviceSetting = deviceSettingMapper.getDeviceSettingByDeviceId(deviceId);
        Integer sleepSwitch = deviceSetting.getSleepSwitch();
        Integer silentShutdownSwitch = deviceSetting.getSilentShutdown();
        Map<String, Object> map = new HashMap<>();
        map.put("sleepMode", sleepSwitch == null ? Constants.SLEEP_SWITCH_CLOSE : sleepSwitch);
        map.put("shutDownSilentMode", silentShutdownSwitch == null ? Constants.SILENT_SHUTDOWN_CLOSE : silentShutdownSwitch);*/
        List<String> typeList = new ArrayList<>();
        typeList.add(Constants.SET_WORK_MODE);
        typeList.add(Constants.AUTO_CHANGE_WORK_MODE);
        typeList.add(Constants.SHUT_DOWN_SILENT);
        //根据imei获取定位模式、睡眠模式的最后一条记录
        List<CommandRecord> list = commandRecordMapper.getSpecialRecordByImei(imei, typeList);
        Map<String, Object> map = new HashMap<>();
        for (CommandRecord record : list) {
            String commandType = record.getCommandType();
            Integer result = record.getResult();
            if (Constants.SET_WORK_MODE.equals(commandType)) {
                map.put("locateMode", result);
            } else if (Constants.AUTO_CHANGE_WORK_MODE.equals(commandType)) {
                map.put("sleepMode", result);
            } else {
                map.put("shutDownSilentMode", result);
            }
        }
        //如果没有下发过指令，则直接返回成功
        if (!map.containsKey("locateMode")) {
            map.put("locateMode", Constants.COMMAND_COMPLETE);
        }
        if (!map.containsKey("sleepMode")) {
            map.put("sleepMode", Constants.COMMAND_COMPLETE);
        }
        if (!map.containsKey("shutDownSilentMode")) {
            map.put("shutDownSilentMode", Constants.COMMAND_COMPLETE);
        }
        return map;
    }

    @Override
    public List<String> getImeiListByDeviceIdList(List<Integer> list) {
        return deviceInfoMapper.getImeiListByDeviceIdList(list);
    }

    @Override
    public Integer bindDevice(Integer stuId, Integer deviceId) {
        return deviceInfoMapper.bindDevice(stuId, deviceId);
    }

    @Override
    public Integer unbindStudentByDeviceId(Integer deviceId) {
        return deviceInfoMapper.unbindStudentByDeviceId(deviceId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer bindDeviceAndSynchronizationOrg(VoStudent voStudent) {
        //获取绑定设备时，设备需要同步的学校
        School school = schoolMapper.getSchoolInfoBySchoolId(voStudent.getSchoolId());
        return deviceInfoMapper.bindDeviceAndSynchronizationOrg(voStudent.getStuId(), voStudent.getDeviceId(), school.getOrgCode(), school.getSchoolName());
    }


    @Override
    public Integer deleteSOSList(Integer deviceId) {
        return deviceInfoMapper.deleteSOSList(deviceId);
    }

    @Override
    public List<Map<String, Object>> getStudentPlaceByDeviceId(List<Integer> list) {
        return deviceInfoMapper.getStudentPlaceByDeviceId(list);
    }

    @Override
    public List<Map<String, Object>> getStudentPlaceByDeviceIdAndH5UserId(List<Integer> list, Integer userId) {
        return deviceInfoMapper.getStudentPlaceByDeviceIdAndH5UserId(list, userId);
    }

    @Override
    public List<Map<String, Object>> getStudentPlaceByStudentId(List<Integer> list) {
        return deviceInfoMapper.getStudentPlaceByStudentId(list);
    }

    @Override
    public int modifyDeviceInfoSetting(DeviceSetting data) {
        return deviceSettingMapper.modifyDeviceSetting(data);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespEntity importCustomerDeviceInfo(MultipartFile file, HttpServletResponse response) {
        String fileName = file.getOriginalFilename();
        if (!ExcelUtils.validateExcel(fileName)) {
            return new RespEntity(RespCode.FILE_FORMAT_ERROR);
        }
        //导出失败信息记录
        List<ExcelImportCustomerDeviceInfo> failMessages = new ArrayList<>();
        //导出失败文件信息
        String path = "";
        //记录需要添加设备信息
        List<DeviceInfo> deviceInfos = new ArrayList<>();
        //读取文件信息
        List<ExcelImportCustomerDeviceInfo> excelImportCustomerDeviceInfos = null;
        try {
            excelImportCustomerDeviceInfos = MyExcelUtils.importExcel(file, 1, 1, ExcelImportCustomerDeviceInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (excelImportCustomerDeviceInfos != null && excelImportCustomerDeviceInfos.size() > 0) {
            aa:
            for (ExcelImportCustomerDeviceInfo importCustomerDeviceInfo : excelImportCustomerDeviceInfos) {
                if (importCustomerDeviceInfo.getCustomerId() == null || StringUtils.isBlank(importCustomerDeviceInfo.getImei()) || StringUtils.isBlank(importCustomerDeviceInfo.getModel())) {
                    ExcelImportCustomerDeviceInfo excelImportCustomerDeviceInfo1 = new ExcelImportCustomerDeviceInfo();
                    excelImportCustomerDeviceInfo1.setCustomerId(importCustomerDeviceInfo.getCustomerId());
                    excelImportCustomerDeviceInfo1.setImei(importCustomerDeviceInfo.getImei());
                    excelImportCustomerDeviceInfo1.setModel(importCustomerDeviceInfo.getModel());
                    excelImportCustomerDeviceInfo1.setMessage("必传参数为空");
                    failMessages.add(excelImportCustomerDeviceInfo1);
                    continue;
                }
                //鉴别是否存在该客户id
                SysCustomer sysCustomer = customerMapper.getCustomerInfoById(importCustomerDeviceInfo.getCustomerId());
                if (sysCustomer == null) {
                    ExcelImportCustomerDeviceInfo excelImportCustomerDeviceInfo1 = new ExcelImportCustomerDeviceInfo();
                    excelImportCustomerDeviceInfo1.setCustomerId(importCustomerDeviceInfo.getCustomerId());
                    excelImportCustomerDeviceInfo1.setImei(importCustomerDeviceInfo.getImei());
                    excelImportCustomerDeviceInfo1.setModel(importCustomerDeviceInfo.getModel());
                    excelImportCustomerDeviceInfo1.setMessage("不存在该客户");
                    failMessages.add(excelImportCustomerDeviceInfo1);
                    continue;
                }
                //鉴别是否已经存在该imei号
                DeviceInfo deviceInfoByImei = deviceInfoMapper.getDeviceInfoByImei(importCustomerDeviceInfo.getImei());
                if (deviceInfoByImei != null) {
                    ExcelImportCustomerDeviceInfo excelImportCustomerDeviceInfo1 = new ExcelImportCustomerDeviceInfo();
                    excelImportCustomerDeviceInfo1.setCustomerId(importCustomerDeviceInfo.getCustomerId());
                    excelImportCustomerDeviceInfo1.setImei(importCustomerDeviceInfo.getImei());
                    excelImportCustomerDeviceInfo1.setModel(importCustomerDeviceInfo.getModel());
                    excelImportCustomerDeviceInfo1.setMessage("已经存在该imei号的设备");
                    failMessages.add(excelImportCustomerDeviceInfo1);
                    continue;
                }
                //excel中是否重复导入
                if (deviceInfos != null && deviceInfos.size() > 0) {
                    for (DeviceInfo deviceInfo : deviceInfos) {
                        if (deviceInfo.getImei().equals(importCustomerDeviceInfo.getImei())) {
                            ExcelImportCustomerDeviceInfo excelImportCustomerDeviceInfo1 = new ExcelImportCustomerDeviceInfo();
                            excelImportCustomerDeviceInfo1.setCustomerId(importCustomerDeviceInfo.getCustomerId());
                            excelImportCustomerDeviceInfo1.setImei(importCustomerDeviceInfo.getImei());
                            excelImportCustomerDeviceInfo1.setModel(importCustomerDeviceInfo.getModel());
                            excelImportCustomerDeviceInfo1.setMessage("重复导入imei");
                            failMessages.add(excelImportCustomerDeviceInfo1);
                            continue aa;
                        }
                    }
                }
                //记录可以成功添加的设备
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setImei(importCustomerDeviceInfo.getImei());
                deviceInfo.setModel(importCustomerDeviceInfo.getModel());
                deviceInfo.setCustomerId(importCustomerDeviceInfo.getCustomerId());
                deviceInfo.setCreateTime(new Date().getTime());
                deviceInfo.setUpdateTime(new Date().getTime());
                deviceInfos.add(deviceInfo);
                continue;
            }
        }
        //批量添加设备
        if (deviceInfos != null && deviceInfos.size() > 0) {
            Integer rest = deviceInfoMapper.batchSaveDevice(deviceInfos);
            //批量初始化设备设置表
            deviceSettingMapper.batchInitializeDeviceSetting(deviceInfos);
            //删除缓存中为入库的imei
            List<String> list = new ArrayList<>();
            deviceInfos.stream().forEach(e -> {
                list.add(e.getImei());
            });
            redisService.deleteUnInStorageList(list);
            if (rest <= 0) {
                return new RespEntity(RespCode.FAILED);
            }
        }
        //导出失败文件信息
        Integer failNum = 0;
        if (failMessages != null && failMessages.size() > 0) {
            failNum = failMessages.size();
            path = MyExcelUtils.exportExcel(failMessages, "设备信息", "设备信息", ExcelImportCustomerDeviceInfo.class, "设备文件导入失败信息.xls", response);
        }
        //构建返回值集合
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("path", path);
        restMap.put("failNum", failNum);
        restMap.put("successNum", deviceInfos != null ? deviceInfos.size() : 0);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespEntity importDeviceInfo(MultipartFile file, String orgCode, String orgName, HttpServletResponse response) {
        String fileName = file.getOriginalFilename();
        if (!ExcelUtils.validateExcel(fileName)) {
            return new RespEntity(RespCode.FILE_FORMAT_ERROR);
        }
        //导出失败信息记录
        List<ExcelImportDeviceInfo> failMessages = new ArrayList<>();
        //导出失败文件信息
        String path = "";
        //记录需要添加设备信息
        List<DeviceInfo> deviceInfos = new ArrayList<>();
 /*       String orgCode = (String) orgMap.get("orgCode");
        String orgName = (String) orgMap.get("orgName");*/
        //读取文件信息
        List<ExcelImportDeviceInfo> excelImportDeviceInfos = null;
        try {
            excelImportDeviceInfos = MyExcelUtils.importExcel(file, 1, 1, ExcelImportDeviceInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (excelImportDeviceInfos != null && excelImportDeviceInfos.size() > 0) {
            aa:
            for (ExcelImportDeviceInfo excelImportDeviceInfo : excelImportDeviceInfos) {
                if (StringUtils.isBlank(excelImportDeviceInfo.getImei()) || StringUtils.isBlank(excelImportDeviceInfo.getModel()) || StringUtils.isBlank(excelImportDeviceInfo.getScreen())) {
                    ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setMessage("必传参数为空");
                    failMessages.add(importDeviceInfo);
                    continue;
                }
                DeviceInfo deviceInfoByImei = deviceInfoMapper.getDeviceInfoByImei(excelImportDeviceInfo.getImei());
                if (deviceInfoByImei != null) {
                    ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setMessage("已经存在该imei号的设备");
                    failMessages.add(importDeviceInfo);
                    continue;
                }
                //excel中是否重复导入
                if (deviceInfos != null && deviceInfos.size() > 0) {
                    for (DeviceInfo deviceInfo : deviceInfos) {
                        if (deviceInfo.getImei().equals(excelImportDeviceInfo.getImei())) {
                            ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                            importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                            importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                            importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                            importDeviceInfo.setMessage("重复导入imei号设备");
                            failMessages.add(importDeviceInfo);
                            continue aa;
                        }
                    }
                }
                //是否有屏幕这个字段只能填是或否
                String screen = excelImportDeviceInfo.getScreen();
                if (!("有屏".equals(screen) || "无屏".equals(screen))) {
                    ExcelImportDeviceInfo importDeviceInfo = new ExcelImportDeviceInfo();
                    importDeviceInfo.setImei(excelImportDeviceInfo.getImei());
                    importDeviceInfo.setModel(excelImportDeviceInfo.getModel());
                    importDeviceInfo.setScreen(excelImportDeviceInfo.getScreen());
                    importDeviceInfo.setMessage("未按照规范填写是否有屏");
                    failMessages.add(importDeviceInfo);
                    continue aa;
                }
                //是否支持内嵌app
                String supportPort = excelImportDeviceInfo.getSupportPort();
                //记录可以成功添加的设备
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setImei(excelImportDeviceInfo.getImei());
                deviceInfo.setModel(excelImportDeviceInfo.getModel());
                deviceInfo.setOrgCode(orgCode);
                deviceInfo.setOrgName(orgName);
                deviceInfo.setCreateTime(new Date().getTime());
                deviceInfo.setUpdateTime(new Date().getTime());
                Integer ifScreen = screen.equals("有屏") ? 1 : 0;
                deviceInfo.setIfScreen(ifScreen);
                deviceInfo.setSupportPort("是".equals(supportPort) ? 1 : 0);
                deviceInfos.add(deviceInfo);
                continue;
            }
        }
        //批量添加设备
        if (deviceInfos != null && deviceInfos.size() > 0) {
            Integer rest = deviceInfoMapper.batchSaveDevice(deviceInfos);
            //批量初始化设备设置表
            deviceSettingMapper.batchInitializeDeviceSetting(deviceInfos);
            //删除缓存中为入库的imei
            List<String> list = new ArrayList<>();
            deviceInfos.stream().forEach(e -> {
                list.add(e.getImei());
            });
            redisService.deleteUnInStorageList(list);
        }
        //导出失败文件信息
        Integer failNum = 0;
        if (failMessages != null && failMessages.size() > 0) {
            failNum = failMessages.size();
            path = MyExcelUtils.exportExcel(failMessages, "设备信息", "设备信息", ExcelImportDeviceInfo.class, "设备文件导入失败信息.xls", response);
        }
        //构建返回值集合
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("path", path);
        restMap.put("failNum", failNum);
        restMap.put("successNum", deviceInfos != null ? deviceInfos.size() : 0);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

    @Override
    public DeviceInfo getDeviceInfoByImei(String imei) {
        return deviceInfoMapper.getDeviceInfoByImei(imei);
    }

    @Override
    public Integer updateDeviceInfo(DeviceInfo deviceInfo) {
        return deviceInfoMapper.updateDeviceInfo(deviceInfo);
    }

    @Override
    public RespEntity addClassesPattern(List<DeviceClassPattern> deviceClassPatterns, SysUser sysUser) {
        ArrayList<DeviceClassMode> batchAddList = new ArrayList<>();//批量添加集合
        ArrayList<DeviceClassMode> batchUpdateList = new ArrayList<>();//批量修改集合
        for (DeviceClassPattern deviceClassPattern : deviceClassPatterns) {
            //1.区别新增加部分，和修改部分
            if (deviceClassPattern.getId() != null) {//新增加部分
                //2.一台设备最多10台课堂模式
                List<DeviceClassPattern> classPatterns = deviceClassPatternMapper.getDeviceClassPatternsByDeviceId(deviceClassPattern.getDeviceId());
                if (classPatterns != null && classPatterns.size() >= 10) {
                    return new RespEntity(RespCode.CLASS_PATTERN_MAXED);
                }
                if (classPatterns != null) {
                    //3.同一时间段，不可重复添加课堂模式(开始时间，结束时间一样则不添加)
                    for (DeviceClassPattern classPattern : classPatterns) {
                        if (deviceClassPattern.getBeginTime().equals(classPattern.getBeginTime()) && deviceClassPattern.getEndTime().equals(classPattern.getEndTime())) {
                            return new RespEntity(RespCode.CLASS_PATTERN_EXIST);
                        }
                    }
                }
                //4.查看设备是否在线
                DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByDeviceId(deviceClassPattern.getDeviceId());
                if (deviceInfo == null) {//此处不可能为空
                    return new RespEntity(RespCode.FAILED);
                }
                boolean online = commandSendUtils.deviceOnline(deviceInfo.getImei());
                DeviceClassMode deviceClassMode = new DeviceClassMode();
                //5.数据解析
                List<Integer> sequenceList = classPatterns.stream().map(classPattern -> classPattern.getSequence()).collect(Collectors.toList());
                int sequence = GeneralSequenceUtils.generalSequence(sequenceList);
                String repeatTime = deviceClassPattern.getRepeatTime();
                String commandNumber = CommandNumberUtil.generateDeviceCommandNumber(redisService);
                deviceClassMode.setDeviceId(deviceClassPattern.getDeviceId());
                deviceClassMode.setImei(deviceInfo.getImei());
                deviceClassMode.setCommandNumber(commandNumber);
                deviceClassMode.setStartTime(deviceClassPattern.getBeginTime());
                deviceClassMode.setEndTime(deviceClassPattern.getEndTime());
                deviceClassMode.setRepeatTime(repeatTime);
                deviceClassMode.setOnOff(1);//添加，开启默认模式
                deviceClassMode.setSequence(sequence);
                deviceClassMode.setStatus(Constants.CLASSES_PATTERN_STAY_ADD);
                commandSendUtils.addClassMode(deviceClassMode, online, sysUser.getUserId(), false);
                //记录新添加课堂模式，状态为待添加
                batchAddList.add(deviceClassMode);
            } else {//修改部分
                //鉴别修改后的的时间段，除开自己本身之外是否重复，有重复则不修改
                List<DeviceClassPattern> classPatterns = deviceClassPatternMapper.getDeviceClassPatternsByDeviceId(deviceClassPattern.getDeviceId());
                for (DeviceClassPattern classPattern : classPatterns) {
                    if (!deviceClassPattern.getId().equals(classPattern.getId())) {//如果不是当前课堂模式
                        if (deviceClassPattern.getBeginTime().equals(classPattern.getBeginTime()) && deviceClassPattern.getEndTime().equals(classPattern.getEndTime())) {
                            return new RespEntity(RespCode.CLASS_PATTERN_EXIST);
                        }
                    }
                }
                DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByDeviceId(deviceClassPattern.getDeviceId());
                if (deviceInfo == null) {//此处不可能为空
                    return new RespEntity(RespCode.FAILED);
                }
                boolean online = commandSendUtils.deviceOnline(deviceInfo.getImei());
                DeviceClassMode deviceClassMode = new DeviceClassMode();
                String repeatTime = deviceClassPattern.getRepeatTime();
                String commandNumber = CommandNumberUtil.generateDeviceCommandNumber(redisService);
                deviceClassMode.setId(deviceClassPattern.getId());
                deviceClassMode.setDeviceId(deviceClassPattern.getDeviceId());
                deviceClassMode.setImei(deviceInfo.getImei());
                deviceClassMode.setCommandNumber(commandNumber);
                deviceClassMode.setStartTime(deviceClassPattern.getBeginTime());
                deviceClassMode.setEndTime(deviceClassPattern.getEndTime());
                deviceClassMode.setRepeatTime(repeatTime);
                deviceClassMode.setOnOff(1);//添加，开启默认模式
                deviceClassMode.setSequence(deviceClassPattern.getSequence());
                deviceClassMode.setStatus(Constants.CLASSES_PATTERN_STAY_UPDATE);
                commandSendUtils.updateClassMode(deviceClassMode, online, sysUser.getUserId(), false);
                //记录修改的课堂模式
                batchUpdateList.add(deviceClassMode);
            }
        }
        if (batchAddList != null && batchAddList.size() > 0) {//执行批量添加假操作
            deviceClassPatternMapper.batchAddClassesPattern(batchAddList);
        }
        if (batchUpdateList != null && batchUpdateList.size() > 0) {//执行批量修改操作
            deviceClassPatternMapper.batchUpdateClassesPattern(batchUpdateList);
        }
        return new RespEntity(RespCode.SUCCESS);
    }

    @Override
    public DeviceInfo getDeviceInfoByDeviceId(Integer deviceId) {
        return deviceInfoMapper.getDeviceInfoByDeviceId(deviceId);
    }

    @Override
    public DeviceInfo getDeviceByImei(String imei) {
        return deviceInfoMapper.getDeviceInfoByImei(imei);
    }

    @Override
    public Integer modifyDeviceInfo(DeviceInfo deviceInfo) {
        return deviceInfoMapper.modifyDeviceInfo(deviceInfo);
    }

    @Override
    public List<Map<String, Object>> getOffLineBufferCmd(String imei) {
        return offLineBufferCmdMapper.getOffLineBufferCmd(imei);
    }

    @Override
    public Integer deleteOffLineBufferCmd(String imei) {
        return offLineBufferCmdMapper.deleteOffLineBufferCmd(imei);
    }


    @Override
    public Map<String, Object> getCustomerDeviceList(Integer customerId, String imei, Integer currPage, Integer pageSize) {
        IPage<Map<String, Object>> page = new Page<>(currPage, pageSize);
        IPage<Map<String, Object>> customerDeviceList = deviceInfoMapper.getCustomerDeviceList(page, imei, customerId);
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("deviceList", null);
        if (customerDeviceList != null) {
            List<Map<String, Object>> records = customerDeviceList.getRecords();
            List<String> imeis = records.stream().map(e -> (String) e.get("imei")).collect(Collectors.toList());
            Map<String, Boolean> stringBooleanMap = deviceFlagService.bathGetDeviceOnline(imeis);
            for (Map<String, Object> record : records) {
                if (record.get("command_number") == null) {
                    record.put("modeStatus", 1);   // 正常
                } else {
                    record.put("modelStatus", 0);   // 待生效
                }
                boolean isOnline = stringBooleanMap.get((String) record.get("imei"));
                record.put("isOnline", isOnline);
                record.remove("command_number");
            }
            result.put("total", customerDeviceList.getTotal());
            result.put("deviceList", records);
        }
        return result;
    }

    @Override
    public Integer deleteAffectionByDeviceId(Integer deviceId) {
        return deviceInfoMapper.deleteAffectionByDeviceId(deviceId);
    }

    @Override
    public Integer deleteWhiteListByDeviceId(Integer deviceId) {
        return deviceInfoMapper.deleteWhiteListByDeviceId(deviceId);
    }

    @Override
    public Integer deleteClassPatternByDeviceId(Integer deviceId) {
        return deviceInfoMapper.deleteClassPatternByDeviceId(deviceId);
    }


    @Override
    public DeviceInfo verifyDeviceCustomer(String imei, Integer customerId) {
        DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByImei(imei);
        if (customerId.equals(deviceInfo.getCustomerId())) {
            return deviceInfo;
        }
        return null;
    }

    @Override
    public LocationDataVo getDeviceLastLocation(String imei) {
        return locationMapper.getDeviceLastLocationDataByImei(imei);
    }

    @Override
    public List<LocationDataVo> getDeviceOrbit(String imei, Long beginTime, Long endTime) {
        return locationMapper.getDeviceOrbit(imei, beginTime, endTime);
    }

    @Override
    public int updateDeviceMode(String imei, Integer mode, Integer interval, String commandNumber) {
        return deviceInfoMapper.updateDeviceMode(imei, mode, interval, commandNumber);
    }

    @Override
    public int updateDeviceModeStatus(String imei, String commandNumber) {
        return 0;
    }

    @Override
    public DeviceInfo getDeviceInfoByStuId(Integer stuId) {
        return deviceInfoMapper.getDeviceInfoByStuId(stuId);
    }

    /**
     * 构建返回数据
     *
     * @return
     */
    public Map<String, Object> disposalData(IPage<Map<String, Object>> iPage) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> records = iPage.getRecords();
        long total = iPage.getTotal();
        map.put("total", total);
        map.put("list", records);
        return map;
    }

    /**
     * 判断设备是否在线
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    public boolean deviceOnline(String imei) {
        boolean isOnline = redisService.hasKey(Constants.DEVICE_ONLINE_PREFIX + imei);
        return isOnline;
    }
}

